package com.zch.mobile;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.dialect.PaginationSupport;
import com.base.mobile.MobException;
import com.base.mobile.MobileInfo;
import com.base.mobile.server.annotation.Mobile;
import com.base.mobile.server.annotation.MobileMethod;
import com.base.util.DateUtil;
import com.bf.common.proto.MChat.MChatDept;
import com.bf.common.proto.MChat.MChatDeptList;
import com.bf.common.proto.MChat.MChatMsg;
import com.bf.common.proto.MChat.MChatMsgList;
import com.bf.common.proto.MChat.MChatView;
import com.bf.common.proto.MChat.MChatViewList;
import com.bf.common.proto.MCommon.MNotify;
import com.bf.common.proto.MCommon.MNotifyList;
import com.bf.common.proto.MCommon.MRet;
import com.bf.common.proto.MUserAccount.SUser;
import com.bf.common.proto.MUserAccount.SUserList;
import com.item.dao.model.User;
import com.item.dao.model.UserNotify;
import com.item.dao.model.UserNotifyExample;
import com.item.daoEx.model.UserEx;
import com.item.service.MessageService;
import com.item.service.UserNotifyService;
import com.item.service.UserService;
import com.item.util.QueryParams;
import com.social.mobile.MSocialError;
import com.zch.dao.model.ChatDept;
import com.zch.dao.model.ChatDeptExample;
import com.zch.dao.model.ChatMsg;
import com.zch.dao.model.ChatView;
import com.zch.daoEx.model.ChatMsgEx;
import com.zch.service.ChatDeptService;
import com.zch.service.ChatDeptUserService;
import com.zch.service.ChatMsgService;
import com.zch.service.ChatNotifyService;
import com.zch.service.ChatViewService;

@Mobile
@Component
public class MAppChat {
	
	@Autowired
	private UserService userService;
	@Autowired
	private ChatViewService chatViewService;
	@Autowired
	private ChatMsgService chatMsgService;
	@Autowired
	private ChatDeptService chatDeptService;
	@Autowired
	private ChatDeptUserService chatDeptUserService;
	@Autowired
	private ChatNotifyService chatNotifyService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private UserNotifyService userNotifyService;
	
	/**
	@api MChatDeptList MChatDeptList	政企互动-部门列表
	@return MChatDeptList
	*/
	@MobileMethod(methodno = "MChatDeptList")
	public MChatDeptList.Builder chatDeptList() throws Exception {
		ChatDeptExample example = new ChatDeptExample();
		example.createCriteria().andCodeNotEqualTo("100").andCodeNotEqualTo("101");
		example.setOrderByClause("sort_order");
		List<ChatDept> list = chatDeptService.selectByExample(example);
		
		MChatDeptList.Builder ret = MChatDeptList.newBuilder();
		for (ChatDept dept : list){
			MChatDept.Builder mini = MChatDept.newBuilder();
			mini.setCode(dept.getCode());
			mini.setName(dept.getName());
			mini.setColor(dept.getStyle());
			ret.addDept(mini);
		}
		return ret;
	}

	/**
	@api MChatUserList MChatUserList	//政企互动-部门人员
	@param required string code			//部门编号
	@return SUserList
	*/
	@MobileMethod(methodno = "MChatUserList")
	public SUserList.Builder chatUserList(MobileInfo mobileInfo, String code) throws Exception {
		if (StringUtils.isBlank(code)) throw new MobException("code");
		QueryParams.Builder builder = QueryParams.newBuilder();
		builder.put("code", code);
		List<UserEx> list = userService.selectChatUserList(builder);
		SUserList.Builder ret = SUserList.newBuilder();
		for (UserEx ex : list){
			SUser.Builder mini = SUser.newBuilder();
			mini.setDeptName(ex.getDeptName());
			mini.setId(ex.getId());
			mini.setFirmAddress(ex.getFirmAddress());
			mini.setFirmName(ex.getFirmName());
			mini.setHeadImg(ex.getHeadImg());
			mini.setNickName(ex.getNickName());
			mini.setType(ex.getType());
			mini.setJob(ex.getJob());
			ret.addUsers(mini);
		}
		return ret;
	}

	
	/**
	@api MChatViewInfo MChatViewInfo	//会话信息(登陆)
	@param required string id		//用户id
	@return MChatView
	*/
	@MobileMethod(methodno = "MChatViewInfo", isLogin = true)
	public MChatView.Builder chatViewInfo(MobileInfo mobileInfo, String id) throws Exception {
		if (StringUtils.isBlank(id)) throw new MobException("id");
		if (mobileInfo.getUserid().equals(id)){
			throw new MobException(MZchError.CHAT_SELF_ERROR);
		}
		String viewId = userService.getViewId(mobileInfo.getUserid(), id);
		ChatView view = new ChatView();
		view.setId(viewId);
		int update = chatViewService.updateByPrimaryKeySelective(view);
		if (update == 0){
			view.setUserId(mobileInfo.getUserid());
			view.setTargetId(id);
			chatViewService.insert(view);
		}else {
			view = chatViewService.selectByPrimaryKey(viewId);
		}
		
		MChatView.Builder ret = MChatView.newBuilder();
		ret.setId(viewId);
		
		User one = userService.selectByPrimaryKey(view.getUserId());
		User two = userService.selectByPrimaryKey(view.getTargetId());
		if (one == null || two == null){
			throw new MobException(MZchError.CHAT_USER_NULL);
		}
		
		SUser.Builder me = SUser.newBuilder();
		SUser.Builder tar = SUser.newBuilder();
		if (mobileInfo.getUserid().equals(one.getId())){
			me.setId(one.getId());
			me.setNickName(one.getNickName());
			me.setHeadImg(one.getHeadImg());
			tar.setId(two.getId());
			tar.setNickName(two.getNickName());
			tar.setHeadImg(two.getHeadImg());
		}else {
			me.setId(two.getId());
			me.setNickName(two.getNickName());
			me.setHeadImg(two.getHeadImg());
			tar.setId(one.getId());
			tar.setNickName(one.getNickName());
			tar.setHeadImg(one.getHeadImg());
		}
		ret.setMe(me);
		ret.setTar(tar);
		return ret;
	}

	/**
	@api MChatViewList MChatViewList	//我的会话列表(登陆)
	@return MChatViewList
	*/
	@MobileMethod(methodno = "MChatViewList", isLogin = true)
	public MChatViewList.Builder chatViewList(MobileInfo mobileInfo) throws Exception {
		MChatViewList.Builder ret = MChatViewList.newBuilder();
		
		return ret;
	}

	/**
	@api MChatMsgListByUser MChatMsgListByUser	//获取消息列表()
	@param required string id	//会话id
	@param optional string time	//传空获取最近10条,msg.time
	@return MChatMsgList
	*/
	@MobileMethod(methodno = "MChatMsgList", isLogin = true)
	public MChatMsgList.Builder chatMsgListByUser(MobileInfo mobileInfo, String id, String time,String msgId) throws Exception {
		if (StringUtils.isBlank(id)) throw new MobException("id");
		QueryParams.Builder builder = QueryParams.newBuilder();
		builder.put("id", id);
		if (StringUtils.isNotBlank(time)){
			if (StringUtils.isBlank(msgId)){
				throw new MobException("msgId");
			}
			builder.put("t", DateUtil.strToDate(time, DateUtil.YYSS));
			PaginationSupport.byId(10, msgId);
		}else {
			PaginationSupport.byPage(1, 10, false);
		}
		List<ChatMsgEx> list = chatMsgService.selectMsgList(builder);
		Collections.reverse(list);
		MChatMsgList.Builder ret = MChatMsgList.newBuilder();
		for (ChatMsgEx ex : list){
			MChatMsg.Builder mini = MChatMsg.newBuilder();
			mini.setMsg(ex.getMsg());
			mini.setTime(DateUtil.dateToStr(ex.getCreateTime(), DateUtil.YYSS));
			mini.setViewId(ex.getViewId());
			mini.setId(ex.getId());
			mini.setImgs(ex.getImgs());
			SUser.Builder u = SUser.newBuilder();
			u.setId(ex.getUserId());
			u.setHeadImg(ex.getHeadImg());
			u.setNickName(ex.getNickName());
			mini.setUser(u);
			ret.addMsg(mini);
		}
		return ret;
	}
	
	/**
	@api MChatMsgAdd MChatMsgAdd	//发送消息(登陆)
	@param required string id	//会话id
	@param required number type	//1文字消息
	@param required string msg	//内容
	@return MRet
	*/
	@MobileMethod(methodno = "MChatMsgAdd", isLogin = true)
	public MRet.Builder chatMsgAdd(MobileInfo mobileInfo, String id, Integer type, String msg, String imgs) throws Exception {
		if (StringUtils.isBlank(id)) throw new MobException("id");
		if (StringUtils.isBlank(msg) && StringUtils.isBlank(imgs)) throw new MobException("msg or imgs");
		
		if (StringUtils.isNotBlank(msg)){
			if (msg.getBytes("utf-8").length > 1000){
				throw new MobException(MZchError.CHAT_LENGTH_OUT);
			}
		}
		type = 1;
		
//		ChatView view = chatViewService.selectByPrimaryKey(id);
//		if (view == null){
//			throw new MobException(MZchError.CHAT_USER_NULL);
//		}
		
		User user = userService.selectByPrimaryKey(id);
		if (user == null){
			throw new MobException(MZchError.CHAT_USER_NULL);
		}
		User user2 = userService.selectByPrimaryKey(mobileInfo.getUserid());
		
		ChatMsg chatMsg = new ChatMsg();
		chatMsg.setIsShow(1);
		chatMsg.setMsg(msg);
		chatMsg.setMsgType(type);
		chatMsg.setUserId(mobileInfo.getUserid());
		chatMsg.setTargetId(id);
		chatMsg.setViewId(id);
		chatMsg.setImgs(imgs);
		int c = chatMsgService.insert(chatMsg);
		if (c == 0){
			throw new MobException(MZchError.CHAT_SEND_ERROR);
		}
		
		//可接入推送
		if (mobileInfo.getUserid().equals(id)){
			//被咨询人
			List<String> users = chatMsgService.selectUserList(id);
			messageService.findMessages(id, user2.getNickName()+"("+user2.getAccount()+")"+"回复了咨询", users, 4);
			
		}else{
			//咨询人
			messageService.findMessage(id, user2.getNickName()+"("+user2.getAccount()+")"+"咨询了问题", id, 3);
		}
		
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(1);
		ret.setMsg(chatMsg.getId());
		return ret;
	}
	
	/**
	@api MChatNotifyList MChatNotifyList	//消息通知(登陆,分页)
	@return MChatNotifyList
	*/
	@MobileMethod(methodno = "MChatNotifyList", isLogin = true, isPage = true)
	public MNotifyList.Builder chatNotifyList(MobileInfo mobileInfo, Integer page, Integer limit) throws Exception {
		MNotifyList.Builder ret = MNotifyList.newBuilder();
		//通知设为已读
		UserNotifyExample example = new UserNotifyExample();
		example.createCriteria().andUserIdEqualTo(mobileInfo.getUserid());
		UserNotify record = new UserNotify();
		record.setIsRead(1);
		userNotifyService.updateByExampleSelective(record, example);
		
		PaginationSupport.byPage(page, limit, false);
		/*MessageExample example = new MessageExample();
		example.or().andTypeEqualTo(1).andStateEqualTo(2);
		example.or().andTargetEqualTo(mobileInfo.getUserid());
		example.setOrderByClause("create_time desc");
		List<Message> list = messageService.selectByExample(example);*/
		example.clear();
		example.setOrderByClause("create_time desc");
		example.createCriteria().andUserIdEqualTo(mobileInfo.getUserid());
		List<UserNotify> list = userNotifyService.selectByExample(example);
		for (UserNotify message : list){
			MNotify.Builder mini = MNotify.newBuilder();
			mini.setId(message.getId());
			mini.setContent(message.getContent());
			mini.setCreateTime(DateUtil.dateToStr(message.getCreateTime(), DateUtil.YYMMMM));
			mini.setRedirectContent(message.getRedirectContent());
			mini.setRedirectType(message.getRedirectType());
			ret.addNotify(mini);
			ret.setCount(list.size()+"");
		}
		
		return ret;
	}
	
	/**
	 * 获取用户信息
	 * 
	 * @param id
	 * @url /mobile?methodno=SGetUserInfo&debug=1&deviceid=test&appid=1&content=
	 */
	@MobileMethod(methodno = "MChatUserInfo", isLogin = false)
	public SUser.Builder getUserInfo(MobileInfo mobileInfo, String id) throws Exception {
		if (StringUtils.isBlank(id)) {
			throw new MobException("id");
		}
		UserEx user = userService.selectChatUserInfo(id);
		if (user == null)
			throw new MobException(MSocialError.USER_NOT_EXISTS);
		SUser.Builder ret = SUser.newBuilder();
		ret.setHeadImg(user.getHeadImg());
		ret.setId(user.getId());
		ret.setNickName(user.getNickName());
		ret.setJob(user.getJob());
		ret.setType(user.getType());
		ret.setDeptName(user.getDeptName());
		ret.setFirmName(user.getFirmName());
		ret.setFirmAddress(user.getFirmAddress());
		return ret;
	}
	
	
}
